package com.cy.mall.service.dda.impl;

import com.cy.mall.comm.constant.Constants;
import com.cy.mall.comm.utils.JsonObjectMapper;
import com.cy.mall.dao.mapper.order.OrderGoodsExtraInfoMapper;
import com.cy.mall.model.Result;
import com.cy.mall.model.dto.order.PushLoanOrderInfoToDdaDTO;
import com.cy.mall.service.BaseService;
import com.cy.mall.service.dda.DdaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @Description 与贷贷安系统进行数据同步的接口实现类
 * @Author tanyilin
 * @Date 2019/8/22 15:05
 */
@Slf4j
@Service
public class DdaServiceImpl extends BaseService implements DdaService {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private OrderGoodsExtraInfoMapper orderGoodsExtraInfoMapper;

    @Value("${dda.push-loan-order-info-url}")
    private String pushLoanOrderInfoUrl;

    @Override
    @Async(Constants.ASYNC)
    public void pushLoanOrderInfo(String loanId) {

        //查询需要推送的订单数据
        PushLoanOrderInfoToDdaDTO pushLoanOrderInfo = orderGoodsExtraInfoMapper.selectPushLoanOrderInfoToDdaDTO(loanId);
        //最终请求的json数据
        String requestJson = JsonObjectMapper.toJson(pushLoanOrderInfo);

        //设置 HttpHeaders、HttpEntity
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> httpEntity = new HttpEntity<>(requestJson, headers);
        //发送post请求
        log.info("推送放款成功订单数据至贷贷安系统，请求 url = {}", pushLoanOrderInfoUrl);
        log.info("推送放款成功订单数据至贷贷安系统，请求报文 = {}", requestJson);
        ResponseEntity<String> responseEntity = restTemplate.exchange(pushLoanOrderInfoUrl, HttpMethod.POST, httpEntity, String.class);

        if (!HttpStatus.OK.equals(responseEntity.getStatusCode())) {
            log.info("放款订单数据[loanId = {}]推送至贷贷安系统，异常", loanId);
        }
        log.info("推送放款成功订单数据至贷贷安系统，回调报文 = {}", responseEntity.getBody());
        Result result = JsonObjectMapper.read(responseEntity.getBody(), Result.class);
        if(result.isOk()) {
            log.info("放款订单数据[loanId = {}]推送至贷贷安系统，成功", loanId);
        }else {
            log.info("放款订单数据[loanId = {}]推送至贷贷安系统，失败", loanId);
        }

    }
}
